<template>
  <div v-loading="loading" class="app-main-content-box">

    <!--filter区域-->
    <div class="filter-content">

      <el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
        <div class="flexRSS">
          <div>
            <el-form-item
              :rules="[
                { required: true, message: '时间区间不能为空'}
              ]"
              label="核销时间："
              prop="date"
            >
              <el-date-picker
                v-model="filterForm.date"
                :default-time="['00:00:00', '23:59:59']"
                type="datetimerange"
                range-separator="~"
                value-format="yyyy-MM-dd HH:mm:ss"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              />
            </el-form-item>
            <el-form-item label="卡号：" prop="cardNo">
              <el-input v-model="filterForm.cardNo" style="width:400px" placeholder="请输入" />
            </el-form-item>
            <el-form-item label="订单号：" prop="orderNo">
              <el-input v-model="filterForm.orderNo" style="width:400px" placeholder="请输入" />
            </el-form-item>

          </div>
          <div>
            <el-form-item label="核销业务：" prop="bizCode">
              <el-select v-model="filterForm.bizCode" filterable placeholder="请选择" style="width:400px">
                <el-option label="所有" value="" />
                <el-option
                  v-for="(item, index) in manageBizCodeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="核销来源：" prop="sourceCode">
              <el-select v-model="filterForm.sourceCode" filterable placeholder="请选择" style="width:400px">
                <el-option label="所有" value="" />
                <el-option
                  v-for="(item, index) in sourceCodeOptions"
                  :key="index"
                  :label="item.label"
                  :value="item.key"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="核销终端：" prop="endpoint">
              <el-input v-model="filterForm.endpoint" style="width:400px" maxlength="40" placeholder="请输入" />
              <!--              <el-select v-model="filterForm.endpoint" filterable placeholder="可通过终端名/终端编号搜索" style="width: 400px">-->
              <!--                <template-->
              <!--                  v-for="item in $store.state.user-->
              <!--                  .allManageDeviceFilterOptions">-->
              <!--                  <el-option-->
              <!--                    v-if="-->
              <!--                      filterForm.shopId === '' ||-->
              <!--                        item.shopId == filterForm.shopId ||-->
              <!--                        item.kdDeviceNo == ''-->
              <!--                    "-->
              <!--                    :key="item.id"-->
              <!--                    :label="-->
              <!--                      item.kdDeviceNo === ''-->
              <!--                        ? item.deviceName-->
              <!--                        : item.deviceName + '(' + item.kdDeviceNo + ')'-->
              <!--                    "-->
              <!--                    :value="item.kdDeviceNo"/>-->
              <!--                </template>-->
              <!--              </el-select>-->
            </el-form-item>

          </div>
        </div>
        <el-form-item label="核销方：" prop="merchant">
          <el-cascader
            v-model="filterForm.merchantArr"
            :options="[{id:'',name:'所有'}].concat(allAuthMchOptions)"
            :props="{ checkStrictly: true,value:'id',label:'name',children:'shops' }"
            style="width:400px"
            clearable
          />
        </el-form-item>

        <el-form-item class="filter-btn">
          <el-button type="primary" round @click="submitForm">查 询</el-button>
          <el-button round @click="resetForm">重 置</el-button>
          <!-- <el-button v-if="!$store.getters.banBtnList.includes('BTN_COUPON_RECEIVE_DETAIL_EXPORT')" round @click="downExcel">导 出</el-button> -->
        </el-form-item>
      </el-form>
    </div>

    <AppTableStatisticsCard :statistics-card-data="statisticsCardData" />

    <div class="table-content">
      <el-table :data="list" size="small" border stripe style="width: 100%" empty-text="暂无数据">
        <el-table-column label="核销流水号/时间" fixed="left">
          <template slot="header">
            <div>核销流水号</div>
            <div>时间</div>
          </template>
          <template slot-scope="scope">
            <div>{{ scope.row.serialNo }}</div>
            <div>{{ scope.row.createTime }}</div>
            <!--            <div v-if="scope.row.cardType==='gift'">{{ scope.row.totalAmount/100+'元 / '+ (scope.row.totalAmount- scope.row.usedAmount)/100 }}元</div>-->
            <!--            <div v-if="scope.row.cardType==='times'">{{ scope.row.totalAmount +'次 / '+ scope.row.totalAmount- scope.row.usedAmount }}次</div>-->
          </template>
        </el-table-column>
        <el-table-column label="卡ID/总次数/剩余">
          <template slot="header">
            <div>卡ID</div>
            <div>总数 / 剩余</div>
          </template>
          <template slot-scope="scope">
            <div>{{ scope.row.cardNo }}</div>
            <!--            <div v-if="scope.row.cardType==='gift'">{{ scope.row.totalAmount/100+'元 / '+ (scope.row.totalAmount- scope.row.verifyAmount)/100 }}元</div>-->
            <div v-if="scope.row.cardType==='gift'">{{ scope.row.totalAmount/100+'元 / '+ scope.row.leftAmount/100 }}元</div>
            <!--            <div v-if="scope.row.cardType==='times'">{{ scope.row.totalAmount +'次 / '+ (scope.row.totalAmount- scope.row.verifyAmount) }}次</div>-->
            <div v-if="scope.row.cardType==='times'">{{ scope.row.totalAmount +'次 / '+ scope.row.leftAmount }}次</div>
          </template>
        </el-table-column>
        <el-table-column label="核销数">
          <template slot-scope="scope">
            <div v-if="scope.row.cardType==='gift'">{{ scope.row.verifyAmount/100 }} 元</div>
            <div v-if="scope.row.cardType==='times'">{{ scope.row.verifyAmount }}次</div>
          </template>
        </el-table-column>
        <el-table-column label="核销方/核销门店/核销人/核销终端">
          <template slot="header">
            <!--            <div>核销方 / 核销门店 / 核销人</div>-->
            <div>核销方 / 核销门店 </div>
            <div>核销终端</div>
          </template>
          <template slot-scope="scope">
            <div>{{ (scope.row.businessName||'无')+' / '+(scope.row.shopName||'无') }}</div>
            <div>{{ `${scope.row.endpointName}${scope.row.endpoint|| ''}` }}</div>
          </template>
        </el-table-column>
        <el-table-column label="核销业务/核销来源/业务订单号">
          <template slot="header">
            <div>核销业务 / 核销来源</div>
            <!--            <div>业务订单号</div>-->
          </template>
          <template slot-scope="scope">
            <div>{{ (bizCodeKeyOptions[scope.row.bizCode]||'无')+' / '+(sourceCodeKeyOptions[scope.row.sourceCode]||'无') }}</div>
          </template>
        </el-table-column>
        <el-table-column prop="customerName" label="顾客" />
        <el-table-column prop="remark" label="备注" />
      </el-table>
      <!-- 分页 -->
      <pagination-direction
        v-if="paginationConfig.total!==0"
        :config="paginationConfig"
        @sizeschange="sizesChange"
        @pagechange="pageChange"
      />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { cardVerifyCount, cardVerifyList } from '../../../api/card'
import { authMerchants } from '../../../api/mch'

export default {
  props: {
    cardPrototype: {
      require: true,
      type: Object
    }
  },
  data() {
    return {
      // 配置
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      statusOptions: {
        1: '待使用',
        2: '已使用',
        3: '已用完',
        4: '已过期'
      },
      unitOptions: {
        gift: '元',
        times: '次'
      },
      allAuthMchOptions: [],
      // 状态
      loading: false,
      // 数据
      statisticsCardData: [],
      list: [],
      filterForm: {
        date: [
          this.$momentMini().format('YYYY-MM-DD') + ' 00:00:00',
          this.$momentMini().format('YYYY-MM-DD') + ' 23:59:59'
        ],
        start: null,
        end: null,
        cardNo: '',
        bizCode: '',
        sourceCode: '',
        cardId: '',
        endpoint: '',
        merchantArr: [''],
        orderNo: '',
        shopId: ''
      }
    }
  },
  computed: {
    ...mapGetters([
      'manageBizCodeOptions',
      'bizCodeKeyOptions',
      'sourceCodeOptions',
      'sourceCodeKeyOptions'
    ])
  },
  watch: {},
  created() {
  },
  mounted() {
    this.getAuthMerchants()
    this.fetchData()
  },
  methods: {
    /**
     * 数据组
     */
    fetchData(
      page = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      this.$refs.filterForm.validate((valid) => {
        if (valid) {
          let params = {}
          params = Object.assign({}, this.filterForm)
          params.page = page
          params.pageSize = pageSize
          params.start = params.date[0]
          params.end = params.date[1]
          params.cardId = this.cardPrototype.id
          if (params.merchantArr) {
            if (params.merchantArr.length === 1) {
              params.merchant = params.merchantArr[0] || ''
              params.shopId = ''
            } else if (params.merchantArr.length === 2) {
              params.merchant = params.merchantArr[0]
              params.shopId = params.merchantArr[1]
            }
          }
          console.log(params)
          delete params.merchantArr
          delete params.date
          // 清除多余字段
          for (const key in params) {
            if (params[key] === '' || params[key] === 'all') {
              delete params[key]
            }
          }
          this.loading = true
          Promise.all([this.getList(params), this.getCount(params)]).then(
            (res) => {
              this.loading = false
            }
          )
        }
      })
    },

    // 获取列表
    getList(params) {
      return new Promise((resolve, reject) => {
        cardVerifyList(params)
          .then((res) => {
            this.list = res.data.list
            this.paginationConfig.total = res.data.total
            this.paginationConfig.page = res.data.pageNum
          })
          .finally(() => {
            resolve()
          })
      })
    },

    // 获取统计
    getCount(params) {
      return new Promise((resolve, reject) => {
        if (params.page !== 1) {
          resolve()
        } else {
          this.statisticsCardData = [
            {
              title: '已使用数',
              value: 0,
              describeList: [],
              detailList: []
            }, {
              title: '已使用的卡数 / 张',
              value: 0,
              describeList: [],
              detailList: []
            }
          ]
          cardVerifyCount(params)
            .then((res) => {
              const unit = this.unitOptions[this.cardPrototype.cardType]
              if (this.cardPrototype.cardType === 'gift') res.data.verifyAmount = res.data.verifyAmount / 100
              this.statisticsCardData[0].title = '已使用数 / ' + unit
              this.statisticsCardData[0].value = res.data.verifyAmount
              this.statisticsCardData[1].value = res.data.cardNum
            })
            .finally(() => {
              resolve()
            })
        }
      })
    },

    // 获取合作商户
    getAuthMerchants() {
      return new Promise((resolve) => {
        authMerchants({ belongMerchant: this.cardPrototype.belongMerchant }).then(res => {
          this.allAuthMchOptions = res.data
        }).finally(() => {
          resolve()
        })
      })
    },
    /**
     * 按钮组
     */
    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 查询
    submitForm() {
      this.fetchData(1)
    },

    // 重置
    resetForm() {
      this.$refs.filterForm.resetFields()
    }
    /**
     * 状态组
     */
    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
/* 筛选 */
.filter-container {
  .filter-btn {
    margin-bottom: 20px;
  }

  .check-all {
    margin-right: 30px;
  }

  // 单选换行
  .el-radio + .el-radio {
    margin-left: 0;
  }

  .el-radio {
    margin-right: 10px;
    height: 32px;
    line-height: 32px;
  }
}

/* 表格 */
.table-content {
  margin-top: 10px;
}
</style>
